import java.io.*;
import java.security.Key;
import java.util.Scanner;

public class Find2 {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入目录：");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        File find = new File(s);

        if(!find.exists()) {
            System.out.println("目录不存在");
            return;
        }
        if(!find.isDirectory()) {
            System.out.println("输入的不是有效目录");
            return;
        }

        System.out.println("输入指定字符：");
        String Key = scanner.nextLine();

        if( Key == null || Key.isEmpty()) {
            System.out.println("输入的字符为空");
            return;
        }

        Find(find,Key);
        scanner.close();
    }

    private static void Find(File find, String key) throws IOException {
        File[] files = find.listFiles();

        if(files.length <= 0) {
            return;
        }
        for(File file : files) {
            if(file.isFile()) {
                //文件
                Boolean bool = checkFile(file,key);
                if(!bool) {
                    continue;
                }
                System.out.println("找到了文件：" + file.getCanonicalPath() +
                        " 包含关键字：" + key + "，是否删除（Y/N）");
                Scanner scanner = new Scanner(System.in);
                String next = scanner.nextLine();
                if(next.toLowerCase().equals("y")) {
                     file.delete();
                    System.out.println("已删除..");
                }
                scanner.close();
            } else {
                Find(file,key);
            }
        }
    }

    private static Boolean checkFile(File file, String key) {
        if(file.getName().contains(key)) {
            return true;
        }
        try (InputStream InputStream = new FileInputStream(file)){
            StringBuilder stringBuilder = new StringBuilder();
            Scanner scanner = new Scanner(InputStream);
            while (true) {
                if(!scanner.hasNextLine()) {
                    break;
                }
                stringBuilder.append(scanner.nextLine());
            }
            if(stringBuilder.indexOf(key) > -1) {
                return true;
            }
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
